#include <iostream>
#include <vector>
#include <unordered_map>
#include <windows.h>
using namespace std;

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> arr;
        vector<int> ans;
        int max_arr=0;

        for(int e:nums)
        {
            arr[e]++;
            max_arr=max(max_arr,arr[e]);
        }

        vector<vector<int>> buf(max_arr+1);
        for(auto& [x,c]:arr)
        {
            buf[c].push_back(x);
        }

        for(int i=max_arr;i>=0&&ans.size()<k;i--)
        {
            ans.insert(ans.end(),buf[i].begin(),buf[i].end());
        }
        return ans;

    }
};

void printResult(const vector<int>& result) {
    cout << "[";
    for (int num : result) {
        cout << num << ",";
    }
    if (!result.empty()) {
        cout << "\b";  // 删除最后一个逗号
    }
    cout << "]" << endl;
}

int main() {
    SetConsoleOutputCP(CP_UTF8);
    Solution s;
    
    // 测试用例1：标准情况
    vector<int> nums1 = {1,1,1,2,2,3};
    cout << "测试用例1 - 常见情况：" << endl;
    cout << "输入：nums = [1,1,1,2,2,3], k = 2" << endl;
    cout << "输出：";
    printResult(s.topKFrequent(nums1, 2));
    cout << "预期：[1,2]" << endl << endl;
    
    
    // 测试用例2：k等于unique数字个数
    vector<int> nums3 = {1,2,3,4};
    cout << "测试用例2 - k等于不同数字个数：" << endl;
    cout << "输入：nums = [1,2,3,4], k = 4" << endl;
    cout << "输出：";
    printResult(s.topKFrequent(nums3, 4));
    cout << "预期：[1,2,3,4]" << endl << endl;
    
    
    // 测试用例3：包含负数
    vector<int> nums4 = {-1,-1,2,2,2,-3};
    cout << "测试用例3 - 包含负数：" << endl;
    cout << "输入：nums = [-1,-1,2,2,2,-3], k = 2" << endl;
    cout << "输出：";
    printResult(s.topKFrequent(nums4, 2));
    cout << "预期：[2,-1]" << endl;


    return 0;
}
